package 第十一章_网络编程.第十一章_网络编程_MINA;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class client {
    public static void main(String[] args) {
        //创建连接
        NioSocketConnector connector=new NioSocketConnector();
        DefaultIoFilterChainBuilder chain =connector.getFilterChain();
        //记得打开过滤器 1.文本2.对象
        //chain.addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory()));
        chain.addLast("objectfilter",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        connector.setHandler(new MinaclientHandler());
        connector.setConnectTimeoutMillis(10000);
        //连接服务器
        ConnectFuture cf=connector.connect(new InetSocketAddress("localhost",9999));
        cf.awaitUninterruptibly();//等待连接
        Scanner input=new Scanner(System.in);
        while(true) {
            //1.文本  2.对象
//            System.out.println("请输入: ");
//            String info = input.nextLine();
//            cf.getSession().write(info);
            //以对象的方式传输数据
            Message msg=new Message();
            System.out.println("from: ");
            msg.setFrom(input.nextLine());
            System.out.println("to: ");
            msg.setTo(input.nextLine());
            System.out.println("info: ");
            msg.setInfo(input.nextLine());
            msg.setType("send");
            cf.getSession().write(msg);


        }
        //等待服务器连接关闭，结束长连接
        //cf.getSession().getCloseFuture().awaitUninterruptibly();
        //connector.dispose();
    }

}
